<script setup lang="tsx">
import { reactive, ref, watch } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessage } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { useStorage } from '@/hooks/web/useStorage'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useUserStore } from '@/store/modules/user'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { MobileLoginType } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import { smsSendApi } from '@/api/common'
import { useIntervalFn } from '@vueuse/core'

const { required } = useValidator()

const emit = defineEmits(['to-register'])

const appStore = useAppStore()

const permissionStore = usePermissionStore()

const userStore = useUserStore()

const { currentRoute, addRoute, push } = useRouter()

const { setStorage } = useStorage()

const { t } = useI18n()

const rules = {
  mobile: [required()],
  smsCode: [required()]
}

const time = ref(0)
const { pause, resume } = useIntervalFn(
  () => {
    time.value--
    if (time.value <= 0) {
      pause()
    }
  },
  1000,
  undefined
)

const smsSend = async () => {
  const formData = await getFormData<MobileLoginType>()
  if (formData.mobile && formData.mobile.length) {
    if (time.value <= 0) {
      const res = await smsSendApi(formData.mobile, 2)
      ElMessage.success(res.data || '发送成功')
      time.value = 60
      resume()
    }
  } else {
    ElMessage.error(t('login.mobilePlaceholder'))
  }
}

const schema = reactive<FormSchema[]>([
  {
    field: 'mobile',
    // label: t('login.mobile'),
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: t('login.mobilePlaceholder')
    }
  },
  {
    field: 'smsCode',
    // label: t('login.code'),
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: t('login.codePlaceholder'),
      slots: {
        append: (
          <ElButton type="primary" onClick={smsSend}>
            {time.value <= 0 ? t('login.fetchCode') : `${time.value}s`}
          </ElButton>
        )
      }
    }
  },
  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <ElButton loading={loading.value} type="primary" class="w-[100%]" onClick={signIn}>
                  {t('login.login')}
                </ElButton>
              </div>
              <div class="w-[100%] mt-15px hidden">
                <ElButton class="w-[100%]" onClick={toRegister}>
                  {t('login.register')}
                </ElButton>
              </div>
            </>
          )
        }
      }
    }
  }
])

const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

const loading = ref(false)

const redirect = ref<string>('')

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

// 登录
const signIn = async () => {
  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<MobileLoginType>()

      try {
        const res = await userStore.mobileLogin(formData)
        if (res && res.code === 200) {
          setStorage(appStore.getUserInfo, res.data)
          // 是否使用动态路由
          if (appStore.getDynamicRouter) {
            // getRole()
          } else {
            // 商家手机号登录，读取商家账户中心路由
            await permissionStore.generateRoutes('static', res.data.perms).catch(() => {})
            permissionStore.getAddRouters.forEach((route) => {
              addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
            })
            permissionStore.setIsAddRouters(true)
            push({ path: redirect.value || permissionStore.addRouters[0].path })
          }
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 去注册页面
const toRegister = () => {
  emit('to-register')
}
</script>

<template>
  <Form
    :schema="schema"
    :rules="rules"
    label-position="top"
    hide-required-asterisk
    size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
    @register="formRegister"
  />
</template>
